use salvo::prelude::*;
use crate::utils::jwt::Claims;

use salvo::extra::jwt_auth::*;
use std::marker::PhantomData;
use jsonwebtoken::{encode, decode, Header, Algorithm, Validation, EncodingKey,TokenData, DecodingKey};
use std::time::{Duration, SystemTime};
use chrono::prelude::*;
//jwt验证 handler 
pub fn create_jwt_auth_handler() -> JwtHandler<Claims> {

    let jwt_auth_config =JwtConfig{
        secret : "123".to_owned(),
        context_token_key : Some("user_token".to_owned()),
        context_state_key : Some("user_token_auth_state".to_owned()),
        context_data_key : Some("user_token_decode_data".to_owned()),
        response_error : true,
        claims :PhantomData::<Claims>,
        //validation : Validation {leeway: 60*60 /*60秒*60 =60分钟*/, ..Default::default()},//HS256
        validation : Validation::default(),//默认 HS256 解码验证方式
        extractors : vec![Box::new(HeaderExtractor::new())],//从 header分解 获取token
    };

    JwtHandler::<Claims>::new(jwt_auth_config)
}

#[fn_handler]
pub async fn jwt_token(_req: &mut Request, _depot: &mut Depot, res: &mut Response) {
    let my_claims =Claims{
        sub: "test1".to_owned(),
        company: "test1".to_owned(),
        //超时时间：当前时间+1000*60*60毫秒
        exp: ( (Local::now().timestamp_millis()+1000*60*60) as usize),
    };
    //secret +盐  123
    let s=encode(&Header::default(), &my_claims, &EncodingKey::from_secret("123".as_ref())).unwrap();

    res.render_plain_text(&s);
}


#[fn_handler]
pub async fn jwt_hello(_req: &mut Request, depot: &mut Depot, res: &mut Response) {
    
    res.render_plain_text(&format!("{:?}",&depot.take::<TokenData<Claims>>(&"user_token_decode_data".to_owned())));
}